package com.hejun.jwt_security.controller;

import com.hejun.jwt_security.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LoginController {

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;
    @PostMapping("/login")
    public String login(String username,String password){

        UserDetails user=userDetailsService.loadUserByUsername(username);
        if (user==null){
            return"账户不存在";
        }
        if (!passwordEncoder.matches(password,user.getPassword())){
            return "密码错误";
        }

        String token = JwtUtils.getToken(username);

        //将生成的Token存入security中
        UsernamePasswordAuthenticationToken authenticationToken= new UsernamePasswordAuthenticationToken(username,password,user.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        return token;
    }
}
